<script setup lang='ts'>
import type { FieldValues, PlusColumn } from 'plus-pro-components'

import { useGetConstructUnitListOptions, useGetPropertyListOptions, usePropertyShow, useUnitPropertyAllSave } from '@fl/api/fit-old-api'
import { SearchTable, SubmitBtn } from '@fl/components'
import { cloneDeep } from 'lodash-es'

const { go } = useRouter()
const form = ref()

const route = useRoute()
const propertyEnterpriseId = ref(route.params?.id as string) // 物业id

const initialState = {
    statePropertyId: '',
}
const state = ref<FieldValues>(cloneDeep(initialState))

watchEffect(() => {
    if (propertyEnterpriseId.value) {
        state.value = {
            statePropertyId: propertyEnterpriseId.value,
        }
    }
})

// 物业公司列表
const { data: propertyOptions, isLoading: propertyListLoading } = useGetPropertyListOptions()

// 施工单位列表
const { data: constructionUnitOptions, isLoading: constructionUnitListLoading } = useGetConstructUnitListOptions()
const constructionUnitDict = computed(() => {
    return constructionUnitOptions.value?.reduce((accr, cur) => {
        accr[cur.value] = cur.label
        return accr
    }, {})
})

// 编辑表单 - 物业公司的详情
const { data: propertyInfo, isLoading: detailLoading } = usePropertyShow(propertyEnterpriseId)

// 保存
const { isPending, mutate: allMutate } = useUnitPropertyAllSave()

// 施工单位的反显
const unitList = ref<any>([])
watchEffect(() => {
    if (propertyInfo.value) {
        const list = cloneDeep(propertyInfo.value?.constructions) || []
        unitList.value = list.reduce((accr, cur) => {
            cur.value = cur.enterpriseId
            cur.label = cur.enterpriseName
            accr.push(cur)
            return accr
        }, [])
    }
})

const fieldProps = computed(() => {
    if (propertyEnterpriseId.value) {
        return {
            disabled: true,
        }
    }
    else {
        return {
            filterable: true,
        }
    }
})

const isLoading = computed(() => {
    const selectLoading = propertyListLoading.value || detailLoading.value || constructionUnitListLoading.value
    return selectLoading
})

function goBack() {
    go(-1)
}

function cancel() {
    goBack()
}

function reset() {
    unitList.value = []
    form.value.formInstance.resetFields()
}

// 新增时候推一条空数据
function goToAdd() {
    console.log('unitList', unitList.value)
    unitList.value.push({
        id: `${new Date().getTime()}`,
        label: '',
        value: '',
    })
}

function addRecord(optionV: string, row: any) {
    const targetIndex = unitList.value.findIndex((v: any) => v.id === row.id)

    unitList.value.splice(targetIndex, 1, cloneDeep({
        id: row.id,
        label: constructionUnitDict.value[optionV],
        value: optionV,
    }))
}

// 一站式保存
async function confirm() {
    // console.log('confirm', state.value, unitList.value)
    const valid = await form.value.formInstance.validate()
    if (valid) {
        if (unitList.value.length === 0) {
            ElMessage({
                message: '施工单位不能为空',
                type: 'warning',
            })
            return
        }
        // 施工单位列表
        const list = unitList.value.reduce((pre, cur) => {
            cur.enterpriseId = cur.value
            cur.enterpriseName = cur.label
            cur.id = String(cur.id).length >= 10 ? null : cur.id // 临时去掉时间戳生成的id
            // 去重
            const duplicate = pre.find(item => item.value === cur.value)
            if (!duplicate) {
                pre.push(cur)
            }
            return pre
        }, [])
        const propertyId = state.value.statePropertyId || propertyEnterpriseId.value
        const property = propertyOptions.value.find((v: any) => v.value === propertyId)
        const params = {
            id: propertyInfo.value?.id,
            list,
            propertyEnterpriseId: property.value,
            propertyEnterpriseName: property.label,
        }
        // console.log('params', params)
        allMutate(params, {
            onSuccess: () => {
                ElMessage.success('操作成功')
                reset()
                cancel()
            },
        })
    }
}

// 前端伪删除
function confirmDelete(row) {
    const targetIndex = unitList.value.findIndex((v: any) => v.id === row.id)
    unitList.value.splice(targetIndex, 1)
}

const columns: PlusColumn[] = [
    {
        colProps: {
            span: 16,
        },
        fieldProps,
        label: '物业单位',
        options: propertyOptions,
        prop: 'statePropertyId',
        valueType: 'select',
    },
]

const rules = {
    statePropertyId: [
        {
            message: '请选择物业公司',
            required: true,
        },
    ],
}

const gridOptions = reactive<any>({
    columns: [
        { slots: { default: 'select' }, title: '施工单位' },
        { slots: { default: 'operate' }, title: '操作', width: 200 },
    ],
})
</script>

<template>
    <ElCard shadow="never">
        <el-button @click="goBack">
            返回列表
        </el-button>

        <ElSkeleton v-if="isLoading"
                    animated
                    class="mt-20"
        />

        <template v-else>
            <div class="mt-20">
                <PlusForm ref="form"
                          v-model="state"
                          :columns="columns"
                          :label-width="100"
                          :rules="rules"
                          :has-footer="false"
                />
            </div>

            <SearchTable v-bind="gridOptions"
                         :loading="isLoading"
                         :data="unitList"
            >
                <template #toolbar_buttons>
                    <ElButton type="primary"
                              @click="goToAdd"
                    >
                        <div class="i-ic:baseline-add size-16" />
                        新增
                    </ElButton>
                </template>

                <template #select="{ row }">
                    <el-select v-model="row.value"
                               placeholder="请选择"
                               filterable
                               @change="addRecord($event, row)"
                    >
                        <el-option v-for="item in constructionUnitOptions"
                                   :key="item.value"
                                   :label="item.label"
                                   :value="item.value"
                        />
                    </el-select>
                </template>

                <template #operate="{ row }">
                    <el-space>
                        <el-popconfirm title="要删除吗？"
                                       @confirm="confirmDelete(row)"
                        >
                            <template #reference>
                                <el-button text
                                           type="warning"
                                           :loading="isPending"
                                >
                                    删除
                                </el-button>
                            </template>
                        </el-popconfirm>
                    </el-space>
                </template>
            </SearchTable>

            <div class="mx-auto mt20 flex justify-center">
                <el-button @click="cancel">
                    取消
                </el-button>

                <SubmitBtn type="primary"
                           :loading="isPending"
                           @click="confirm"
                >
                    提交
                </SubmitBtn>
            </div>
        </template>
    </ElCard>
</template>
